# sync/base_sync.py
import abc
from abc import ABC
from typing import List, Any

from aop.aop_config import load_global_config
from services.prod.prod_service import ProdService
from utils.log_utils import get_logger

# 获取一个命名的日志记录器
logger = get_logger(__name__)


class BaseSync(ABC):
    @load_global_config('../config/config.json5')
    def __init__(self, prod_service: ProdService, dev_service):
        self.prod_service = prod_service
        self.dev_service = dev_service

    def get_items(self, start_time, end_time, page_num: int, page_size: int, session=None) -> List[Any]:
        return self.prod_service.get_items(start_time, end_time, page_num=page_num, page_size=page_size,
                                           session=session)

    def delete_dev_data(self, start_time, end_time):
        if start_time is None or end_time is None:
            self.dev_service.delete_all()
            logger.info(f"{self.prod_service.get_table_name()} 表数据已全部删除")
            return
        self.dev_service.delete(start_time, end_time)


    @abc.abstractmethod
    def insert_dev_data(self, items: List[Any], session=None):
        raise NotImplementedError

    def show_total_count(self, start_time, end_time, ):
        total_count = self.prod_service.get_total_count(start_time, end_time)
        logger.info(
            f" 表名：{self.prod_service.get_table_name()} ,查询字段 {self.prod_service.time_field} 生产总记录数: {total_count}")

    def get_total_ids(self, start_time, end_time):
        """
        获取所有的 ID
        :param start_time:
        :param end_time:
        :return:
        """
        with self.prod_service.get_session() as prod_session:
            return self.prod_service.get_total_ids(start_time, end_time, session=prod_session)

    def sync_page(self, start_time, end_time, page_size=10000):
        with self.prod_service.get_session() as prod_session, \
                self.dev_service.get_session() as dev_session:

            total_count = self.prod_service.get_total_count(start_time, end_time, session=prod_session)
            logger.info(f"{self.prod_service.get_table_name()} 总记录数: {total_count}")
            if total_count <= 0:
                logger.info("无数据需要同步")
                return

            total_page = (total_count + page_size - 1) // page_size
            logger.info(f"总页数: {total_page}")
            for page_num in range(total_page):
                logger.info(f"正在处理 {self.prod_service.get_table_name()} ,第 {page_num + 1} / {total_page} 页")
                items = self.get_items(start_time, end_time, page_num, page_size, session=prod_session)
                logger.info(f"获取到{self.prod_service.get_table_name()} , {len(items)} 条记录")
                self.insert_dev_data(items, session=dev_session)
                logger.info(f"{self.prod_service.get_table_name()} 第 {page_num + 1} 页处理完成,总数 {total_count}")

    def __enter__(self):
        # 初始化资源
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # 清理资源
        self.prod_service.close_session()
        self.dev_service.close_session()
        return False  # 不自动抑制异常
